<?php

namespace app\api\controller;

use app\facade\Redis;
use app\models\{User as Users, Config, Region, Riderlist, RiderStreet, OrderProduct, Order, Graborder, Message, Coupon, Pkey, Promo, Agent as Agents, RiderMoneyLog};
use think\Facade\Config as Configs;
use app\facade\Mns;
use think\Validate;
use think\Db;
use EasyWeChat\Factory;
use think\facade\Log;


class Rider extends Base
{


    public function rinvitlist()
    {
        $list = [
            'money' => $this->request->reder['money'], //余额
            'income' => 0, //洗车收益
            'tdzincome' => 0, //团队长收益
            'riderlist' => [] // 邀请骑手
        ];
        $list['income'] = (new RiderMoneyLog())->where(['type' => 1, 'user_id' => $this->request->reder_id])->sum('money');
        $list['tdzincome'] = (new RiderMoneyLog())->where(['type' => 2, 'user_id' => $this->request->reder_id])->sum('money');
        //团队成员
        $riderlist = (new Riderlist())->where('pid', $this->request->reder_id)->select();
        foreach ($riderlist as $rider) {
            $list['riderlist'][] = [
                'name' => $rider['name'],
                'mobile' => $rider['mobile'],
                'incomeing' => (new Order())->where(['orderid' => $rider['id'], 'porderid' => $this->request->reder_id, 'status' => 3])->sum('priderincome'),
                'incomeend' => (new Order())->where(['orderid' => $rider['id'], 'porderid' => $this->request->reder_id, 'status' => 4])->sum('priderincome'),
            ];
        }
        $this->result($list, 0, '查询完成');
    }

    public function rmoney_log()
    {
        $type = $this->request->get('type/d', 0);
        $model = new RiderMoneyLog();
        $list = $model
            ->where('user_id', $this->request->reder_id)
            ->field('created,info,money')
            ->order('id desc');
        if (!empty($type)) {
            $list = $list->where('type', $type);
        }
        $list = $list->paginate(20, false, ['query' => $this->request->param()]);
        $this->result($list, 0, '获取成功');
    }
    // public function getcode()
    // {
    //     $list = (new Pkey())->where(['rider' => $this->request->reder_id, 'type' => 1, 'status' => [1, 2]])->order('status asc')->field('id,code,status,promoid')->select();
    //     foreach ($list as $lists) {
    //         $lists['status_text']  = '无';
    //         if ($lists['status'] == 1) {
    //             $lists['status_text'] = '待使用';
    //         }
    //         if ($lists['status'] == 2) {
    //             $lists['status_text'] = '已使用';
    //         }
    //         if ($lists['status'] == 3) {
    //             $lists['status_text'] = '已作废';
    //         }
    //         $protitle = (new Promo())->where('id', $lists['promoid'])->value('title') ?? '';
    //         $url = $this->keyhb($lists['id'], $lists['code'], $protitle);
    //         $lists['images'] = $url;
    //     }
    //     $this->result($list, 0, '获取成功');
    // }

    // //生成图片
    // public function keyhb($id = 0, $code = '', $protitle = '')
    // {
    //     $names = './uploads/hechengkeys/alpha_image' . $id . '.jpg'; //合成图片本地路径
    //     $hecheng = url($names, '', '', true); //合成图片url路径
    //     $name = 'pkey' . $id . '.png';
    //     $path =  $_SERVER['DOCUMENT_ROOT'] . "/uploads/pkey/"; //微信小程序码保存
    //     //判断是否已经生成合成图片
    //     if (!file_exists($_SERVER['DOCUMENT_ROOT'] . '/uploads/hechengkeys/alpha_image' . $id . '.jpg')) {
    //         //微信小程序码
    //         try {
    //             if (!is_dir($path)) {
    //                 mkdir($path, 0777, true);
    //             }
    //             $config = config('wechat.');
    //             $app = Factory::miniProgram($config);
    //             $rm = $app->app_code->getUnlimit('keycode=' . $code, [
    //                 'page'  => 'pages/center/warchCard',
    //                 'auto_color' => false,
    //                 'width' => 400
    //             ]);
    //             if ($rm instanceof \EasyWeChat\Kernel\Http\StreamResponse) {
    //                 $rm->save($path, $name);
    //             }
    //         } catch (\Exception $e) {
    //             return false;
    //         }
    //         try {
    //             $image1 = \think\Image::open('./uploads/pkey/' . $name);
    //             $image1->thumb(210, 210)->save('./uploads/pkey/m_' . $name);
    //             $image = \think\Image::open('./true.jpg');
    //             $image->text($protitle . '，兑换码:' . $code, 'rzt.ttf', 24, '#333333', \think\Image::WATER_SOUTHEAST, -20)->water('./uploads/pkey/m_' . $name, [500, 1150], 100)->save($names);
    //         } catch (\Exception $e) {
    //             return false;
    //         }
    //     }
    //     return $hecheng;
    // }

    public function login()
    {
        $data = $this->request->post();
        $validate = new Validate([
            'mobile' => 'require',
            'password' => 'require'
        ], [
            'mobile.require' => '登录手机号不能为空',
            'password.require' => '登录密码不能为空'
        ]);
        if (!$validate->check($data)) {
            $this->result([], 1, $validate->getError());
        }
        $user = (new Riderlist())->where('mobile', $data['mobile'])->find();
        if (empty($user) || $user['password'] != md5(md5($data['password']))) {
            $this->result([], 1, '账号或密码错误');
        }
        $token = 'RIDER' . md5(md5($user['id'] . time()));
        Redis::setex($token, 86400 * 7, $user['id']);
        $this->result(['token' => $token], 0, '登录成功');
    }

    public function orderlist()
    {
        $status = $this->request->get('status/d', 1);
        $keywords = $this->request->get('keywords/s', ''); //搜索关键字
        $lat = $this->request->get('lat', 0) ?? 0;
        $lng = $this->request->get('lng', 0) ?? 0;
        if (empty($lat) || empty($lng)) {
            $lat = 0;
            $lng = 0;
        }
        if (!empty($lat) && !empty($lng)) {
            if ($lat != 'undefined' && $lng != 'undefined') {
                Redis::zAdd('getlatlonarr' . $this->request->reder_id, time(), $lng . ',' . $lat);
                Log::write($lng . ',' . $lat, 'getlons');
            }
            //获取今日内定位信息
            // $startime = strtotime(date('Y-m-d'));
            // $getlats = Redis::zRangeByScore('getlatlonarr' . $this->request->reder_id, $startime, time());
            // dump($getlats);
        }
        $model = (new Order());
        $rider = $this->request->reder;
        $filed = 'ROUND(6371.004*2*ASIN(SQRT(POW(SIN((' . $lat . '*PI()/180-lat*PI()/180)/2),2)+COS(' . $lat . '*PI()/180)*COS(lat*PI()/180)*POW(SIN((' . $lng . '*PI()/180-lon*PI()/180)/2),2)))*100)/100 AS dist';
        $list = $model->field('id,ordersn,ccount,refund,lat,lon,agentid,riderincome,cards,name,info,mobile,color,model,keyss,street,address,posaddress,info,status,issystem,payment,total,ptotal,appointment,created,' . $filed);
        switch ($status) {
            case '1':
                // $street = (new RiderStreet())->distinct(true)->where(['riderid' =>  $this->request->reder_id, 'status' => 2])->column('street');
                $agents = (new RiderStreet())->distinct(true)->where(['riderid' =>  $this->request->reder_id, 'status' => 2])->column('agentid');
                // $list = $list->order(['appointment' => 'asc'])->where(['street' => $street, 'status' => 2, 'agentid' => $agents]);
                $list = $list->order(['dist' => 'asc', 'appointment' => 'asc'])->where(['status' => 2, 'agentid' => $agents]);
                break;
            case '2':
                $list = $list->order(['ordertime' => 'desc'])->where(['orderid' => $rider['id'], 'status' => 3]);
                break;
            case '3':
                $list = $list->order(['endtime' => 'desc'])->where(['orderid' => $rider['id'], 'status' => 4]);
                break;
            default:
                $list = $list->where(['id' => 0]);
                break;
        }
        if (empty($keywords)) {
            $list = $list->where('ordersn|name|mobile|cards', 'like', '%' . $keywords . '%');
        }
        $list = $list->paginate(50, false, ['query' => $this->request->param()]);
        foreach ($list as $lists) {
            $street = getdrees($lists['street'], 2);
            $lists['province_text'] = $street['province'];
            $lists['city_text'] = $street['city'];
            $lists['area_text'] = $street['area'];
            $lists['street_text'] = $street['street'];
            $lists['model_text'] = $lists->model_text;
            $lists['appointment'] = !empty($lists['appointment']) ? $lists['appointment'] : '无';
            $lists['orderproduct'] = (new OrderProduct())->where('ordersn', $lists['ordersn'])->field('id,title,descs,images,price,number,cnumber')->select();
            $lists['status_text'] = $lists->status_text;
            $lists['payment_text'] = $lists->payment_text;
            if ($lists['issystem'] == 2) {
                $lists['street_text'] = '*' . $street['street'];
            }
            if ($lists['dist'] < 100) {
                $lists['posaddress'] = $lists['posaddress'] . '【距你' . $lists['dist'] . '米】';
            }
            //预估收益
            if ($lists['status'] == 2 || $lists['status'] == 3) {
                //代理信息
                $handfee2 = (new Config())->where('name', 'handfee2')->value('value') ?? 65; //骑手比例
                //计算骑手收益
                $riderincome = round(($handfee2 * $lists['ptotal'] / 100), 2);
                //计算团队长收益
                $lists['riderincome'] = $riderincome;
            }
        }
        $this->result($list, 0, '获取成功');
    }


    public function toporderlist()
    {
        $status = $this->request->get('status/d', 1);
        $keywords = $this->request->get('keywords/s', ''); //搜索关键字
        $model = (new Order());
        $rider = $this->request->reder;
        $list = $model->field('id,ordersn,ccount,refund,lat,lon,agentid,priderincome,cards,name,info,mobile,color,model,keyss,street,address,posaddress,info,status,issystem,payment,total,ptotal,appointment,created,orderid');
        switch ($status) {
            case '2':
                $list = $list->order(['ordertime' => 'desc'])->where(['porderid' => $rider['id'], 'status' => 3]);
                break;
            case '3':
                $list = $list->order(['endtime' => 'desc'])->where(['porderid' => $rider['id'], 'status' => 4]);
                break;
            default:
                $list = $list->where(['id' => 0]);
                break;
        }
        if (empty($keywords)) {
            $list = $list->where('ordersn|name|mobile|cards', 'like', '%' . $keywords . '%');
        }
        $list = $list->paginate(50, false, ['query' => $this->request->param()]);
        foreach ($list as $lists) {
            $street = getdrees($lists['street'], 2);
            $lists['province_text'] = $street['province'];
            $lists['city_text'] = $street['city'];
            $lists['area_text'] = $street['area'];
            $lists['street_text'] = $street['street'];
            $lists['model_text'] = $lists->model_text;
            $lists['appointment'] = !empty($lists['appointment']) ? $lists['appointment'] : '无';
            $lists['orderproduct'] = (new OrderProduct())->where('ordersn', $lists['ordersn'])->field('id,title,descs,images,price,number,cnumber')->select();
            $lists['status_text'] = $lists->status_text;
            $lists['payment_text'] = $lists->payment_text;
            if ($lists['issystem'] == 2) {
                $lists['street_text'] = '*' . $street['street'];
            }
            $lists['ridername'] = '';
            $lists['ridermobile'] = '';
            if ($lists['orderid'] > 0) {
                $rider = (new Riderlist())->where('id', $lists['orderid'])->field('name,mobile,riderlat,riderlon')->find();
                $lists['ridername'] = $rider['name'] ?? '';
                $lists['ridermobile'] = $rider['mobile'] ?? '';
            }
            //预估收益
            if ($lists['status'] == 2 || $lists['status'] == 3) {
                //计算团队长收益
                $lists['priderincome'] = 0;
            }
        }
        $this->result($list, 0, '获取成功');
    }

    public function orderdetail()
    {
        $id = $this->request->get('id/d', 0);
        $model = (new Order());
        $rider = $this->request->reder;
        $filed = 'ROUND(6371.004*2*ASIN(SQRT(POW(SIN((' . $rider['riderlat'] . '*PI()/180-lat*PI()/180)/2),2)+COS(' . $rider['riderlat'] . '*PI()/180)*COS(lat*PI()/180)*POW(SIN((' . $rider['riderlon'] . '*PI()/180-lon*PI()/180)/2),2)))*100)/100 AS dist';
        $lists = $model->where('id', $id)->field('id,cmoney,ccount,ordersn,refund,lat,lon,name,mobile,color,model,keyss,street,address,posaddress,info,status,images1,images2,payment,total,ptotal,appointment,cards,created,' . $filed)->find();
        if (empty($lists)) {
            $this->result([], 1, '获取失败');
        }
        $street = getdrees($lists['street'], 2);
        $lists['province_text'] = $street['province'];
        $lists['city_text'] = $street['city'];
        $lists['area_text'] = $street['area'];
        $lists['street_text'] = $street['street'];
        $lists['appointment'] = !empty($lists['appointment']) ? $lists['appointment'] : '无';
        $lists['model_text'] = $lists->model_text;
        $lists['orderproduct'] = (new OrderProduct())->where('ordersn', $lists['ordersn'])->field('id,title,descs,images,price,number,cnumber')->select();
        $lists['status_text'] = $lists->status_text;
        $lists['payment_text'] = $lists->payment_text;
        $images1 = json_decode($lists['images1'] ?? '', true) ?? [];
        $images2 = json_decode($lists['images2'] ?? '', true) ?? [];
        $lists['images1'] = [];
        $lists['images2'] = [];
        if (is_array($images1)) {
            $lists['images1'] = $images1;
        }
        if (is_array($images2)) {
            $lists['images2'] = $images2;
        }
        $this->result($lists, 0, '获取成功');
    }

    public function orders()
    {
        $id = $this->request->get('id/d', 0);
        $order = (new Order())->where(['id' => $id, 'status' => 2])->find();
        if (empty($order)) {
            $this->result([], 1, '订单不存在或用户已取消');
        }
        //判断是否为自己街道订单
        $riderstreet = (new RiderStreet())->where(['riderid' =>  $this->request->reder_id, 'status' => 2, 'agentid' => $order['agentid']])->find();
        if (empty($riderstreet)) {
            $this->result([], 1, '无当前街道接单权限');
        }
        //判断团队长
        $porderid = 0;
        if ($this->request->reder['pid'] > 0) {
            $istdz = (new Riderlist())->where('id', $this->request->reder['pid'])->value('istdz') ?? 1;
            if ($istdz == 2) {
                $porderid = $this->request->reder['pid'];
            }
        }
        Db::startTrans();
        try {
            (new Order())->where(['id' => $order['id'], 'status' => 2])->update(['status' => 3, 'porderid' => $porderid, 'orderid' => $this->request->reder_id, 'ordertime' => date('Y-m-d H:i:s')]);
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->result([], 1, '接单失败，请重试');
        }
        $this->result([], 0, '接单成功');
    }

    public function riderstreet()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'street' => 'require'
            ], [
                'street.require' => '街道ID不能为空'
            ]);
            if (!$validate->check($data)) {
                $this->result([], 1, $validate->getError());
            }
            $data['lat'] = $data['lat'] ?? 0;
            $data['lng'] = $data['lng'] ?? 0;
            $streets = getlatlon($data['lat'], $data['lng'], 3);
            if (empty($streets['street'])) {
                $streets = getdrees($data['street'], 3);
            }
            if (empty($streets['street']) || empty($streets['area']) || empty($streets['city']) || empty($streets['province'])) {
                $this->result([], 1, '地址信息错误，请重新选择或刷新页面重试');
            }
            //代理ID
            if (empty($streets['agentid'])) {
                $this->result([], 1, '当前位置暂未开放申请');
            }
            $data['street'] = $streets['street'];
            $riderid = $this->request->reder_id;
            $haverider = (new RiderStreet())->where(['riderid' => $riderid, 'status' => [1, 2]])->value('agentid') ?? 0;
            if (!empty($haverider) && $streets['agentid'] != $haverider) {
                $this->result([], 1, '此街道与您已申请街道不属于同一管理人员,无法申请');
            }
            $riderstreet = (new RiderStreet())->where(['riderid' => $riderid, 'street' => $streets['street']])->find();
            if (!empty($riderstreet) && $riderstreet['status'] == 1) {
                $this->result([], 1, '当前街道已在审核中，请等待审核');
            }
            if (!empty($riderstreet) && $riderstreet['status'] == 2) {
                $this->result([], 1, '您已有当前街道权限,无需重复申请');
            }
            //保存数据
            $addstreet = [
                'riderid' => $riderid,
                'agentid' => $streets['agentid'] ?? 0,
                'province' => $streets['province'],
                'city' => $streets['city'],
                'area' => $streets['area'],
                'street' => $streets['street'],
                'status' => 1,
                'lat' => $data['lat'],
                'lon' => $data['lng']
            ];
            Db::startTrans();
            try {
                if (empty($riderstreet)) {
                    (new RiderStreet())->allowfield(true)->save($addstreet);
                } else {
                    (new RiderStreet())->allowfield(true)->save($addstreet, ['id' => $riderstreet['id']]);
                }
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                $this->result([], 1, '申请失败，请重试');
            }
            $this->result([], 0, '申请成功，待审核');
        } else {
            $list = (new RiderStreet())->field('street,area,status')->where(['riderid' => $this->request->reder_id])->select();
            foreach ($list as $lists) {
                $address = getdrees($lists['street'], 2);
                $lists['province_text'] = $address['province'];
                $lists['city_text'] = $address['city'];
                $lists['area_text'] = $address['area'];
                $lists['street_text'] = $address['street'];
            }
            $this->result($list, 0, '获取成功');
        }
    }

    public function  message()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'message' => 'require',
                'type' => 'require|in:1,2,3',
            ], [
                'message.require' => '反馈内容为空',
                'type.require' => '反馈类型不能为空',
                'type.in' => '反馈类型不正确',
            ]);
            if (!$validate->check($data)) {
                $this->result([], 1, $validate->getError());
            }
            $data['messtype'] = $data['type'];
            $data['type'] = 2;
            $data['user_id'] = $this->request->reder_id;
            if (!empty($data['images'])) {
                $images = json_decode($data['images'] ?? '', true) ?? [];
                if (is_array($images) && count($images) > 0) {
                    $data['images'] = json_encode($images, true);
                } else {
                    $data['images'] = '';
                }
            } else {
                $data['images'] = '';
            }
            $res = (new Message())->allowfield(true)->save($data);
            if ($res) {
                $this->result([], 0, '提交成功');
            }
            $this->result([], 1, '提交失败');
        } else {
            $list = (new Message())->order('id desc');
            $list = $list->where(['user_id' =>  $this->request->reder_id, 'type' => 2])
                ->field('message,reply,mobile,created,images,messtype,type')
                ->paginate(20, false, ['query' => $this->request->param()])->each(function ($item) use ($list) {
                    $item['images'] = json_decode($item['images'], true) ?? [];
                    $item['type_text'] = $item->type_text;
                    return $item;
                });
            $this->result($list, 0, '查询完成');
        }
    }

    public function  returnorder()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'id' => 'require',
                'mobile' =>  'require',
            ], [
                'id.require' => '订单ID不能为空',
                'mobile.require' => '转让人账号不能为空',
            ]);
            if (!$validate->check($data)) {
                $this->result([], 1, $validate->getError());
            }
            //查看订单是否存在
            $order = (new Order())->where(['id' => $data['id'], 'status' => 3, 'orderid' => $this->request->reder_id])->find();
            if (empty($order)) {
                $this->result([], 1, '订单不可转让');
            }
            if ($data['mobile'] == $this->request->reder['mobile']) {
                $this->result([], 1, '订单不可以转让给自己');
            }
            $user = (new Riderlist())->where(['mobile' => $data['mobile']])->find();
            if (empty($user) || $user['status'] != 1) {
                $this->result([], 1, '转让人不存在或处于不在线状态');
            }
            //判断用户是否存在或有没有接单权限
            $RiderStreet = (new RiderStreet())->where(['riderid' => $user['id'], 'status' => 2])->find();
            if (empty($RiderStreet)) {
                $this->result([], 1, '该师傅无订单所属街道接单权限');
            }
            //判断团队长
            $porderid = 0;
            if ($user['pid'] > 0) {
                $istdz = (new Riderlist())->where('id', $user['pid'])->value('istdz') ?? 1;
                if ($istdz == 2) {
                    $porderid = $user['pid'];
                }
            }
            Db::startTrans();
            try {
                (new Order())->where(['id' => $order['id'], 'status' => 3])->update(['orderid' => $user['id'], 'porderid' => $porderid]);
                (new Graborder())->insert(['user_id' => $user['id'], 'comeuser_id' => $this->request->reder_id, 'orderid' => $order['id'], 'type' => 2]);
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                $this->result([], 1, '转让失败，请重试');
            }
            $this->result([], 0, '转让成功');
        }
    }

    public function confirmorder()
    {
        $data = $this->request->post();
        $validate = new Validate([
            'id' => 'require',
            'status' =>  'require|in:4,5',
        ], [
            'id.require' => '订单id不能为空',
            'status.require' => '操作状态不能为空',
            'status.in' => '操作状态类型不正确',
        ]);
        if (!$validate->check($data)) {
            $this->result([], 1, $validate->getError());
        }
        Log::write($data, 'test');
        $order = (new Order())->where(['id' => $data['id'], 'orderid' => $this->request->reder_id, 'status' => 3])->find();
        if (empty($order)) {
            $this->result([], 1, '订单不存在或不可操作');
        }
        $user = (new Users())->where('id', $order['user_id'])->find();
        $endtime = date('Y-m-d H:i:s');
        $caceltime = date('Y-m-d H:i:s');
        $data['images2'] = $order['images2'];
        if ($data['status'] == 4) {
            if (!empty($data['images'])) {
                if (!is_array($data['images'])) {
                    $images = json_decode($data['images'] ?? '', true) ?? [];
                } else {
                    $images = $data['images'] ?? [];
                }
                if (is_array($images) && count($images) > 0) {
                    $data['images2'] = json_encode($images, true);
                } else {
                    $this->result([], 1, '照片上传出错,请重试或刷新页面');
                }
            } else {
                $this->result([], 1, '请上传清洗后照片');
            }
            $endtime = date('Y-m-d H:i:s');
            $caceltime = $order['caceltime'];
        }
        if ($data['status'] == 5) {
            $endtime = $order['endtime'];
            $caceltime = date('Y-m-d H:i:s');
        }
        $msg = '操作成功';
        $data['refund'] = 1;
        if ($data['status'] == 5 && $order['total'] > 0 && $order['payment'] > 1) {
            $data['refund'] = 2;
            $msg = "取消成功，退款将原路返回";
        }
        $coupon = json_decode($order['coupons'], true) ?? [];
        Db::startTrans();
        try {
            (new Order())->where(['id' => $order['id'], 'status' => 3])->update([
                'refund' => $data['refund'],
                'status' => $data['status'],
                'endtime' => $endtime,
                'caceltime' => $caceltime,
                'images2' => $data['images2']
            ]);
            //积分赠送
            if ($data['status'] == 4 && !empty($user)) {
                (new Users())->IntergralEdit($user['id'], $user['integral'], $order['total'], 1, $order['id'], '下单赠送');
            }
            if ($data['status'] == 5 && $order['coupon'] > 0) {
                (new Coupon())->where('id', $order['coupon'])->update(['status' => 1]);
            }
            if ($data['status'] == 5 && count($coupon) > 0) {
                (new Coupon())->where(['id' => $coupon])->update(['status' => 1]);
            }
            Db::commit();
        } catch (\Exception $e) {
            dump($e->getMessage());
            Db::rollback();
            $this->result([], 1, '操作失败，请重试');
        }
        $this->result([], 0, $msg);
    }

    public function orderupload()
    {
        $data = $this->request->post();
        $validate = new Validate([
            'id' => 'require',
            'images' =>  'require',
        ], [
            'id.require' => '订单id不能为空',
            'images.require' => '照片不能为空',
        ]);
        if (!$validate->check($data)) {
            $this->result([], 1, $validate->getError());
        }
        Log::write($data, 'test');
        $order = (new Order())->where(['id' => $data['id'], 'orderid' => $this->request->reder_id])->find();
        if (empty($order)) {
            $this->result([], 1, '订单不存在或不可操作');
        }
        if (!is_array($data['images'])) {
            $images = json_decode($data['images'] ?? '', true) ?? [];
        } else {
            $images = $data['images'];
        }
        if (is_array($images) && count($images) > 0) {
            $data['images1'] = json_encode($images, true);
        } else {
            $this->result([], 1, '照片上传出错,请重试或刷新页面');
        }
        Db::startTrans();
        try {
            (new Order())->where(['id' => $order['id']])->update([
                'images1' => $data['images1']
            ]);
            Db::commit();
        } catch (\Exception $e) {
            dump($e->getMessage());
            Db::rollback();
            $this->result([], 1, '操作失败，请重试');
        }
        $this->result([], 0, '操作成功');
    }

    public function getstatus()
    {
        $data = $this->request->get();
        $validate = new Validate([
            'status' => 'require|in:1,2,3'
        ], [
            'status.require' => '状态类型不能为空',
            'status.in' => '状态类型错误'
        ]);
        if (!$validate->check($data)) {
            $this->result([], 1, $validate->getError());
        }
        $user = (new Riderlist())->where(['id' => $this->request->reder_id])->find();
        if ($user['status'] == $data['status']) {
            $this->result([], 1, '状态未更改');
        }
        $res = (new Riderlist())->where(['id' => $this->request->reder_id])->update(['status' => $data['status']]);
        if ($res) {
            $this->result([], 0, '更改成功');
        }
        $this->result([], 1, '更改失败，请重试');
    }

    public function getinfo()
    {

        $user = (new Riderlist())->field('id,mobile,name,cards,status,openid,bh')->where(['id' => $this->request->reder_id])->find();
        $user['isgz'] = 1;
        if (empty($user['openid'])) {
            $user['isgz'] = 2;
        }
        $this->result($user, 0, '获取成功');
    }


    public function qrcode()
    {
        $user = $this->request->reder;
        $agentid = (new RiderStreet())->distinct(true)->where(['riderid' =>  $this->request->reder_id, 'status' => 2])->value('agentid') ?? 0;
        $name = 'riders' . $user['id'] . '.png';
        $qcode = url('/rider/' . $name, '', '', true);
        $path =  $_SERVER['DOCUMENT_ROOT'] . "/rider/";
        //二维码已存在且没吵过缓存时间将返回已存在的
        $unique = 'qrcoderider' . $this->request->reder_id;
        $riderqcode = Redis::get($unique);
        if (file_exists($path . $name) && $riderqcode) {
            $this->result($qcode, 0, '获取成功');
        }
        $config = config('wechat.');
        try {
            if (!is_dir($path)) {
                mkdir($path, 0777, true);
            }
            $app = Factory::miniProgram($config);
            $rm = $app->app_code->getUnlimit('rider=' . $user['id'] . '&agentid=' . $agentid, [
                'page'  => 'pages/index/getCoupon',
                'width' => 600,
            ]);
            if ($rm instanceof \EasyWeChat\Kernel\Http\StreamResponse) {
                $rm->save($path, $name);
            }
            Redis::setex($unique, 7200, 7200);
        } catch (\Exception $e) {
            $this->result([], 1, $e->getMessage());
        }
        $this->result($qcode, 0, '获取成功');
    }
}
